// const mySqlServer = require("../mysql/index.js")
const { getFile } = require('../models/getfile')

const model = require('../models/model')
const User = model.user.User
const MyGoods = model.goodsdetails.MyGoods
const MyGoodsListRate = model.goodsdetailsRate.MyGoodsListRate

exports.getDetails = async(ctx) => {
  const { adminId } = ctx.request.body
  if (!adminId) {
    ctx.fail('参数错误', -1)
    return
  }

  // 计算店铺平均评分
  function calculateCount() {
    return new Promise(async(resolve) => {
      let countAll = 0
      const res = await MyGoodsListRate.findAll({ where: { adminId } })
      res.forEach(item => {
        countAll += item.count
      })
      resolve(countAll / res.length)
    })
  }
  const res = await User.findOne({ where: { id: adminId }})
  if (res) {
    res['avatar'] = await getFile(res.avatar)
    res['count'] = await calculateCount()
    ctx.success(res, '成功')
    
  } else {
    ctx.fail('失败', -1)
  }
}

exports.getList = async(ctx) => {
  // 获取 所有商品列表（分页处理）
  const {adminId, page, size} = ctx.request.body
  if (!page || !size || !adminId) {
    ctx.fail('参数错误', -1)
    return
  }
  // 获取商品的相关图片总集
  function getFileAll({ iconId, homeImageIds, detailsImageIds }) {
    return new Promise(async(resolve) => {
      const iconUrl = await getFile(iconId)
      const homeImageUrl = await getFile(homeImageIds)
      const detailsImageUrl = await getFile(detailsImageIds)
      resolve({
        iconUrl,
        homeImageUrl,
        detailsImageUrl
      })
    })
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const res = await MyGoods.findAndCountAll({
        order: [['updateTime', 'DESC']],
        where: { adminId: adminId },
        offset: (page-1) * size,
        limit: parseInt(size)
      })
      if (res.rows.length > 0) {
        let flag = 0
        for (let i = 0; i < res.rows.length; i++) {
          getFileAll(res.rows[i]).then(({ iconUrl, homeImageUrl, detailsImageUrl }) => {
            res.rows[i].iconId = iconUrl
            res.rows[i].homeImageIds = homeImageUrl
            res.rows[i].detailsImageIds = detailsImageUrl
            res.rows[i].none_sku = res.rows[i].none_sku ? true : false
            flag++
            // 异步循环完成
            if (flag === res.rows.length) {
              resolve(res)
            }
          })
        }
        resolve(res)
        return
      }
      resolve(res)
    })
  }
  const res = await allFn()
  if (res != -1) {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}